<template>
  <div class="edit-page-container">
    <!-- 面包屑导航 -->
    <!--    <Breadcrumb :items="breadcrumbItems" />-->

    <div class="content-container">
      <div class="page-title">
        <h3>{{ isEditMode ? '编辑数据' : '新增数据' }}</h3>
      </div>

      <!-- 表单卡片 -->
      <el-card class="form-card">
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="120px"
            class="edit-form"
        >
          <!-- 表单字段 -->
          <el-form-item label="roleName" prop="userName">
            <el-input v-model="formData.roleName" placeholder="请输入" />
          </el-form-item>

          <el-form-item label="moduleUrl" prop="userPassword">
            <el-input v-model="formData.roleCode" placeholder="请输入" />
          </el-form-item>

        </el-form>
        <el-form-item class="form-actions">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="saveData">保存</el-button>
        </el-form-item>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import Breadcrumb from "@/components/breadcrumb/index.vue";
import {ElMessage} from "element-plus";
import api from '@/api/role.ts'
import { log } from 'node:console';
const router = useRouter();
const route = useRoute();
// 表单引用
const formRef = ref(null);

const options = []
// 表单数据
const formData = ref({
  roleId:'',
  roleCode:'',
  roleName:'',
});
let loading =ref(false);
// 表单验证规则
const rules = reactive({
  // name: [
  //   { required: true, message: '请输入名称', trigger: 'blur' },
  //   { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  // ],
  // description: [
  //   { required: true, message: '请输入描述', trigger: 'blur' }
  // ],
  // status: [
  //   { required: true, message: '请选择状态', trigger: 'change' }
  // ],
  // category: [
  //   { required: true, message: '请选择分类', trigger: 'change' }
  // ],
  // date: [
  //   { required: true, message: '请选择日期', trigger: 'change' }
  // ]
});

// 面包屑数据
const breadcrumbItems = [
  { label: '首页', path: '/' },
  { label: '数据管理', path: '/data' },
  // { label: isEditMode ? '编辑数据' : '新增数据' }
];

// 判断是否为编辑模式
const isEditMode = ref("");

// 模拟获取数据
const fetchData =  () => {
  formData.value = JSON.parse(sessionStorage.getItem("role"));
};
// 模拟保存数据 const response = await api.selectAll(params);
// const saveData = async () => {
//    console.log("表单数据",formData.value);
//   let response;
//   // 表单验证
//   formRef.value.validate(async valid => {
//     if (valid) {
//       if (isEditMode.value) {
//         console.log("表单数据",formData.value);
        
//         response = await api.update(formData.value );
//       }else{
//         response = await api.insert(formData.value );
//       }
//       // 显示成功消息
//       ElMessage.success(isEditMode.value ? '数据更新成功' : '数据创建成功');
//       // 返回列表页
//       router.push('/role');
//     }
//   });
// };

const saveData2 = async () => {
  console.log("表单数据", formData.value);
  try {
    // 等待表单验证完成
    const valid = await new Promise(resolve => {
      formRef.value.validate(resolve);
    });
    
    if (valid) {
      console.log("表单验证通过，数据:", formData.value);
      let response;
      if (isEditMode.value) {
        console.log("编辑模式，表单数据:", formData.value);
        response = await api.update(formData.value);
      } else {
        response = await api.insert(formData.value);
      }
      ElMessage.success(isEditMode.value ? '数据更新成功' : '数据创建成功');
      router.push('/user');
    } else {
      console.log("表单验证失败");
      ElMessage.error('表单验证失败，请检查输入');
    }
  } catch (error) {
    console.error("保存数据时发生错误:", error);
    ElMessage.error('保存数据失败');
  }
};

// 取消编辑
const cancelEdit = () => {
  router.push("/role");
};


const getAllMenu = async () => {
  loading.value = true;
  try {
    const response = await api.select({});
    for (const item of  response.list) {
      if( item.parentId == null  ){
        options.push({
          value: item.roleId,
          label:item.roleName
        })
      }
    }
    loading.value = false;
  } catch (error) {
    console.error('加载数据失败:', error);
  }
  if (route.params.id !=null ||route.params.id !=undefined ) {
    isEditMode.value = true;
    const id = route.params.id;
    fetchData(id);
  }else{
    isEditMode.value = false;
  }
};
// 初始化数据
onMounted(() => {
  getAllMenu();

});

// // 监听路由变化，更新面包屑
// watch(
//     () => route.params.id,
//     (newId) => {
//       console.log("newId",newId)
//       isEditMode.value = !!newId;
//       breadcrumbItems[2].label = isEditMode.value ? '编辑数据' : '新增数据';
//
//       if (isEditMode.value) {
//         fetchData(newId);
//       } else {
//         // 重置表单
//         Object.assign(formData, {
//           id: null,
//           name: '',
//           description: '',
//           status: 'active',
//           category: 'category_a',
//           date: null,
//           attachment: null,
//         });
//       }
//     }
// );
</script>

<style scoped>
.edit-page-container {
  padding: 20px;
}

.content-container {
  margin-top: 20px;
}

.page-title {
  margin-bottom: 20px;
}
:deep( .el-card__body ){
  min-height: 61vh;
}
.form-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}
.el-form-item {
  align-items: center;
}
.edit-form {
  width: 50%;
  margin: 53px auto;
}

.form-actions {
  margin-top: 30px;
  text-align: right;
}
.upload-btn {
  display: inline-block;
  vertical-align: middle;
}
:deep(.el-form-item__content) {
  justify-content: center !important;
}
.uploaded-file {
  margin-left: 10px;
  display: inline-block;
  vertical-align: middle;
}
</style>
